<template>
  <el-dialog
    v-model="dialogVisible"
    :title="isEdit ? '编辑调度计划' : '新增调度计划'"
    width="1200px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      class="dispatch-form"
    >
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基本信息 -->
        <el-tab-pane label="基本信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="计划名称" prop="planName">
                <el-input v-model="formData.planName" placeholder="请输入计划名称" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="调度类型" prop="dispatchType">
                <el-select v-model="formData.dispatchType" placeholder="请选择调度类型" style="width: 100%">
                  <el-option label="防洪调度" value="flood-control" />
                  <el-option label="供水调度" value="water-supply" />
                  <el-option label="发电调度" value="power-generation" />
                  <el-option label="生态调度" value="ecological" />
                  <el-option label="综合调度" value="comprehensive" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="优先级" prop="priority">
                <el-select v-model="formData.priority" placeholder="请选择优先级" style="width: 100%">
                  <el-option label="低" value="low" />
                  <el-option label="中" value="medium" />
                  <el-option label="高" value="high" />
                  <el-option label="紧急" value="urgent" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="执行状态" prop="status">
                <el-select v-model="formData.status" placeholder="请选择状态" style="width: 100%">
                  <el-option label="待执行" value="pending" />
                  <el-option label="执行中" value="executing" />
                  <el-option label="已完成" value="completed" />
                  <el-option label="已暂停" value="paused" />
                  <el-option label="已取消" value="cancelled" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="计划执行时间" prop="scheduledTime">
                <el-date-picker
                  v-model="formData.scheduledTime"
                  type="datetime"
                  placeholder="请选择执行时间"
                  style="width: 100%"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="预计持续时间">
                <el-input-number
                  v-model="formData.estimatedDuration"
                  :min="1"
                  :max="9999"
                  placeholder="小时"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-form-item label="调度范围" prop="scope">
            <el-checkbox-group v-model="formData.scope">
              <el-checkbox label="主库区">主库区</el-checkbox>
              <el-checkbox label="副库区">副库区</el-checkbox>
              <el-checkbox label="上游水库">上游水库</el-checkbox>
              <el-checkbox label="下游河道">下游河道</el-checkbox>
              <el-checkbox label="泵站">泵站</el-checkbox>
              <el-checkbox label="闸门">闸门</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          
          <el-form-item label="计划描述">
            <el-input
              v-model="formData.description"
              type="textarea"
              :rows="3"
              placeholder="请输入计划描述"
            />
          </el-form-item>
        </el-tab-pane>

        <!-- 调度参数 -->
        <el-tab-pane label="调度参数" name="parameters">
          <div class="parameter-section">
            <h4>水位控制参数</h4>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="目标水位(m)">
                  <el-input-number
                    v-model="formData.parameters.targetWaterLevel"
                    :precision="2"
                    :step="0.1"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最高水位(m)">
                  <el-input-number
                    v-model="formData.parameters.maxWaterLevel"
                    :precision="2"
                    :step="0.1"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最低水位(m)">
                  <el-input-number
                    v-model="formData.parameters.minWaterLevel"
                    :precision="2"
                    :step="0.1"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          
          <div class="parameter-section">
            <h4>流量控制参数</h4>
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="目标流量(m³/s)">
                  <el-input-number
                    v-model="formData.parameters.targetFlow"
                    :precision="2"
                    :step="1"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最大流量(m³/s)">
                  <el-input-number
                    v-model="formData.parameters.maxFlow"
                    :precision="2"
                    :step="1"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="最小流量(m³/s)">
                  <el-input-number
                    v-model="formData.parameters.minFlow"
                    :precision="2"
                    :step="1"
                    style="width: 100%"
                  />
                </el-form-item>
              </el-col>
            </el-row>
          </div>
          
          <div class="parameter-section">
            <h4>闸门控制参数</h4>
            <div class="gate-controls">
              <div
                v-for="(gate, index) in formData.parameters.gates"
                :key="index"
                class="gate-item"
              >
                <el-row :gutter="10" align="middle">
                  <el-col :span="6">
                    <el-input v-model="gate.name" placeholder="闸门名称" />
                  </el-col>
                  <el-col :span="5">
                    <el-input-number
                      v-model="gate.openingDegree"
                      :min="0"
                      :max="100"
                      placeholder="开度(%)"
                      style="width: 100%"
                    />
                  </el-col>
                  <el-col :span="5">
                    <el-input-number
                      v-model="gate.flow"
                      :precision="2"
                      placeholder="流量(m³/s)"
                      style="width: 100%"
                    />
                  </el-col>
                  <el-col :span="6">
                    <el-select v-model="gate.mode" placeholder="控制模式" style="width: 100%">
                      <el-option label="自动" value="auto" />
                      <el-option label="手动" value="manual" />
                      <el-option label="远程" value="remote" />
                    </el-select>
                  </el-col>
                  <el-col :span="2">
                    <el-button type="danger" size="small" @click="removeGate(index)">
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </el-col>
                </el-row>
              </div>
              <el-button type="primary" size="small" @click="addGate">
                <el-icon><Plus /></el-icon>
                添加闸门
              </el-button>
            </div>
          </div>
        </el-tab-pane>

        <!-- 执行步骤 -->
        <el-tab-pane label="执行步骤" name="steps">
          <div class="steps-section">
            <div class="steps-header">
              <h4>调度执行步骤</h4>
              <el-button type="primary" size="small" @click="addStep">
                <el-icon><Plus /></el-icon>
                添加步骤
              </el-button>
            </div>
            
            <div class="steps-list">
              <div
                v-for="(step, index) in formData.steps"
                :key="index"
                class="step-item"
              >
                <div class="step-header">
                  <span class="step-number">步骤 {{ index + 1 }}</span>
                  <el-button type="danger" size="small" @click="removeStep(index)">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
                
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="步骤名称">
                      <el-input v-model="step.name" placeholder="请输入步骤名称" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="步骤类型">
                      <el-select v-model="step.type" placeholder="请选择类型" style="width: 100%">
                        <el-option label="水位调节" value="water-level" />
                        <el-option label="流量控制" value="flow-control" />
                        <el-option label="闸门操作" value="gate-operation" />
                        <el-option label="泵站启停" value="pump-operation" />
                        <el-option label="监测检查" value="monitoring" />
                        <el-option label="人工确认" value="manual-confirm" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-row :gutter="20">
                  <el-col :span="8">
                    <el-form-item label="负责人">
                      <el-input v-model="step.responsible" placeholder="请输入负责人" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="预计时长(分钟)">
                      <el-input-number
                        v-model="step.estimatedTime"
                        :min="1"
                        style="width: 100%"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="是否必需">
                      <el-switch v-model="step.required" />
                    </el-form-item>
                  </el-col>
                </el-row>
                
                <el-form-item label="步骤描述">
                  <el-input
                    v-model="step.description"
                    type="textarea"
                    :rows="2"
                    placeholder="请输入步骤描述"
                  />
                </el-form-item>
                
                <el-form-item label="执行条件">
                  <el-input
                    v-model="step.conditions"
                    placeholder="请输入执行条件"
                  />
                </el-form-item>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 相关人员 -->
        <el-tab-pane label="相关人员" name="personnel">
          <el-row :gutter="40">
            <el-col :span="12">
              <h4>通知人员</h4>
              <el-transfer
                v-model="formData.notificationPersonnel"
                :data="availablePersonnel"
                :titles="['可选人员', '已选人员']"
                filterable
                filter-placeholder="搜索人员"
              />
            </el-col>
            <el-col :span="12">
              <h4>执行人员</h4>
              <el-transfer
                v-model="formData.executionPersonnel"
                :data="availablePersonnel"
                :titles="['可选人员', '已选人员']"
                filterable
                filter-placeholder="搜索人员"
              />
            </el-col>
          </el-row>
        </el-tab-pane>

        <!-- 附件信息 -->
        <el-tab-pane label="附件信息" name="attachments">
          <div class="attachment-section">
            <div class="upload-area">
              <el-upload
                class="upload-demo"
                drag
                :auto-upload="false"
                :on-change="handleFileChange"
                :file-list="formData.attachments"
                multiple
              >
                <el-icon class="el-icon--upload"><UploadFilled /></el-icon>
                <div class="el-upload__text">
                  将文件拖到此处，或<em>点击上传</em>
                </div>
                <template #tip>
                  <div class="el-upload__tip">
                    支持 jpg/png/gif/pdf/doc/docx/xls/xlsx 文件，且不超过 10MB
                  </div>
                </template>
              </el-upload>
            </div>
            
            <div v-if="formData.attachments.length > 0" class="file-list">
              <h4>已上传文件</h4>
              <el-table :data="formData.attachments" style="width: 100%">
                <el-table-column prop="name" label="文件名" />
                <el-table-column prop="size" label="文件大小">
                  <template #default="{ row }">
                    {{ formatFileSize(row.size) }}
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="100">
                  <template #default="{ row, $index }">
                    <el-button type="danger" size="small" @click="removeFile($index)">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-form>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">
          {{ isEdit ? '更新' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus, Delete, UploadFilled } from '@element-plus/icons-vue'

interface Props {
  visible: boolean
  formData: any
  isEdit: boolean
}

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'save', data: any): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  formData: () => ({}),
  isEdit: false
})

const emit = defineEmits<Emits>()

const formRef = ref()
const activeTab = ref('basic')
const saving = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 表单数据
const formData = reactive({
  planName: '',
  dispatchType: '',
  priority: 'medium',
  status: 'pending',
  scheduledTime: '',
  estimatedDuration: 24,
  scope: [],
  description: '',
  parameters: {
    targetWaterLevel: 0,
    maxWaterLevel: 0,
    minWaterLevel: 0,
    targetFlow: 0,
    maxFlow: 0,
    minFlow: 0,
    gates: []
  },
  steps: [],
  notificationPersonnel: [],
  executionPersonnel: [],
  attachments: []
})

// 表单验证规则
const formRules = {
  planName: [
    { required: true, message: '请输入计划名称', trigger: 'blur' }
  ],
  dispatchType: [
    { required: true, message: '请选择调度类型', trigger: 'change' }
  ],
  priority: [
    { required: true, message: '请选择优先级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择执行状态', trigger: 'change' }
  ],
  scheduledTime: [
    { required: true, message: '请选择计划执行时间', trigger: 'change' }
  ],
  scope: [
    { required: true, message: '请选择调度范围', trigger: 'change' }
  ]
}

// 可选人员数据
const availablePersonnel = ref([
  { key: 1, label: '张三 - 调度员' },
  { key: 2, label: '李四 - 工程师' },
  { key: 3, label: '王五 - 技术员' },
  { key: 4, label: '赵六 - 监测员' },
  { key: 5, label: '孙七 - 维护员' },
  { key: 6, label: '周八 - 安全员' },
  { key: 7, label: '吴九 - 主管' },
  { key: 8, label: '郑十 - 副主管' }
])

// 监听表单数据变化
watch(() => props.formData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    Object.assign(formData, {
      ...newData,
      parameters: {
        targetWaterLevel: 0,
        maxWaterLevel: 0,
        minWaterLevel: 0,
        targetFlow: 0,
        maxFlow: 0,
        minFlow: 0,
        gates: [],
        ...newData.parameters
      },
      steps: newData.steps || [],
      notificationPersonnel: newData.notificationPersonnel || [],
      executionPersonnel: newData.executionPersonnel || [],
      attachments: newData.attachments || []
    })
  } else {
    // 重置表单
    Object.assign(formData, {
      planName: '',
      dispatchType: '',
      priority: 'medium',
      status: 'pending',
      scheduledTime: '',
      estimatedDuration: 24,
      scope: [],
      description: '',
      parameters: {
        targetWaterLevel: 0,
        maxWaterLevel: 0,
        minWaterLevel: 0,
        targetFlow: 0,
        maxFlow: 0,
        minFlow: 0,
        gates: []
      },
      steps: [],
      notificationPersonnel: [],
      executionPersonnel: [],
      attachments: []
    })
  }
}, { immediate: true, deep: true })

// 添加闸门
const addGate = () => {
  formData.parameters.gates.push({
    name: '',
    openingDegree: 0,
    flow: 0,
    mode: 'auto'
  })
}

// 删除闸门
const removeGate = (index: number) => {
  formData.parameters.gates.splice(index, 1)
}

// 添加步骤
const addStep = () => {
  formData.steps.push({
    name: '',
    type: '',
    responsible: '',
    estimatedTime: 30,
    required: true,
    description: '',
    conditions: ''
  })
}

// 删除步骤
const removeStep = (index: number) => {
  formData.steps.splice(index, 1)
}

// 文件上传处理
const handleFileChange = (file: any, fileList: any[]) => {
  formData.attachments = fileList
}

// 删除文件
const removeFile = (index: number) => {
  formData.attachments.splice(index, 1)
}

// 格式化文件大小
const formatFileSize = (size: number) => {
  if (size < 1024) {
    return size + ' B'
  } else if (size < 1024 * 1024) {
    return (size / 1024).toFixed(1) + ' KB'
  } else {
    return (size / (1024 * 1024)).toFixed(1) + ' MB'
  }
}

// 保存
const handleSave = async () => {
  try {
    await formRef.value?.validate()
    
    if (formData.steps.length === 0) {
      ElMessage.warning('请至少添加一个执行步骤')
      activeTab.value = 'steps'
      return
    }
    
    saving.value = true
    
    // 模拟保存延迟
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    emit('save', { ...formData })
    
  } catch (error) {
    console.error('表单验证失败:', error)
  } finally {
    saving.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  formRef.value?.resetFields()
  activeTab.value = 'basic'
  emit('update:visible', false)
}
</script>

<style scoped>
.dispatch-form {
  max-height: 600px;
  overflow-y: auto;
}

.parameter-section {
  margin-bottom: 30px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.parameter-section h4 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.gate-controls {
  margin-top: 15px;
}

.gate-item {
  margin-bottom: 15px;
  padding: 15px;
  background-color: white;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.steps-section {
  padding: 20px;
}

.steps-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.steps-header h4 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.steps-list {
  max-height: 400px;
  overflow-y: auto;
}

.step-item {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.step-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.step-number {
  font-weight: 600;
  color: #409eff;
  font-size: 14px;
}

.attachment-section {
  padding: 20px;
}

.upload-area {
  margin-bottom: 30px;
}

.file-list h4 {
  margin: 0 0 15px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-tabs__content) {
  padding: 20px;
}

:deep(.el-transfer-panel) {
  width: 200px;
}

:deep(.el-upload-dragger) {
  width: 100%;
}

:deep(.el-form-item) {
  margin-bottom: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}
</style>